function new_struct = defstruc(old_struct, field_name, default_value);

% DEFSTRUC - initialize structure with default values if needed
%
%    SNEW = DEFSTRUC(SOLD, FIELD, DEFAULT) insures that all fields
%    in the cell array FIELD are present in SOLD.  If not present,
%    these fields are added to SNEW and initialized with values in
%    the cell array DEFAULT. 

% By:   S.C. Molitor (smolitor@bme.jhu.edu)
% Date: June 11, 1999

if (nargin ~= 3)
   return
elseif (~isempty(old_struct) & ~isstruct(old_struct))
   return
elseif (~iscell(field_name))
   return
elseif (~iscell(default_value))
   return
end

% determine number of fields
% check field names are strings

num_field = min(length(field_name), length(default_value));
for i = 1 : num_field
   if (~ischar(field_name{i}))
      return
   end
end

% make copy of structure
% cannot process structure arrays
% new structure will not be returned if all fields are present

if (length(old_struct) > 1)
   new_struct = old_struct(1);
else
   new_struct = old_struct;
end

% check for field existence
% create field with default value if field doesn't exist

copy_flag = 0;
for i = 1 : num_field
   if (~isfield(new_struct, field_name{i}))
      copy_flag = 1;
      new_struct = setfield(new_struct, field_name{i}, default_value{i});
   end
end

% only return new structure if field didn't exist

if (copy_flag == 0)
   new_struct = old_struct;
end
return
